const {
    Good
} = require('../../model/goods')
const {
    User
} = require('../../model/users')

module.exports = async (req, res) => {
    //获取客户端传递过来的当前页和显示的条数,由于传递过来的是字符串形式，要转换为数字类型
    let page = parseInt(req.query.page)
    let pageSize = parseInt(req.query.pageSize)
    //分页公式
    let skip = (page - 1) * pageSize
    //获取客户端传递过来的升降序的sort
    let sort = req.query.sort
    //接收客户传递过来的价格过滤参数，进行过滤查询
    let priceLevel = req.query.priceLevel
    let priceStart = 0,
        priceEnd = 0;
    //定义查询的条件
    let params = {}
    //如果传递的过滤条件是all，则全部查询，步骤过滤查询处理
    if (priceLevel !== 'all') {
        switch (priceLevel) {
            case '0':
                priceStart = 0;
                priceEnd = 100;
                break;
            case '1':
                priceStart = 100;
                priceEnd = 500;
                break;
            case '2':
                priceStart = 500;
                priceEnd = 1000
                break;
            case '3':
                priceStart = 1000;
                priceEnd = 5000;
                break;
        }
        params = {
            //让价格作为查询条件，大于开始值，小于结束值
            salePrice: {
                $gt: priceStart,
                $lte: priceEnd
            }
        }
    }

    //数据总条数
    let total = await Good.countDocuments()
    //根据条件查询数据7
    let goods = Good.find(params).skip(skip).limit(pageSize)
    //对查询返回的数据进行排序 默认升序，要降序sort给-1

    goods.sort({
        'salePrice': sort
    })
    //执行返回的数据
    goods.exec(function (err, doc) {
        if (err) {
            res.json({
                status: 400,
                msg: err.message
            })
        } else {
            res.json({
                status: 200,
                msg: '获取成功',
                data: {
                    count: doc.length,
                    list: doc
                },
                total
            })
        }
    })

}